<?php

namespace App\Http\Controllers\Test;


use App\Http\Controllers\Controller;
use PhpOffice\PhpWord\PhpWord;


class PhpWordController extends Controller
{

    /**
     * phpword文档
     * https://www.kancloud.cn/shuiyueju/phpword16/1118692
     */

    // word操作管理
    public function initialize()
    {
        parent::initialize();
    }

    // html转换word（成功）
    public function html()
    {
        $html    = '<div style="font-size: 32px;">标题</div><p style="color: red;">描述</p><img src="https://slh.caitongnews.com/app/2023/202307/05/202307051688544173.6837653323704.jpg?imageMogr2/auto-orient/thumbnail/690" /><a href="https://www.baidu.com/">https://www.baidu.com/</a>';
        $phpWord = new PhpWord();
        $section = $phpWord->addSection();

        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');
        $filename  = 'html转换的.docx';
        $objWriter->save($filename);

        return $this->success([], 'html转换word成功');
    }

    // html转换word并下载（成功）
    public function downHtml()
    {
        $filename = 'html转换的.docx';
        header('Content-Type: application/vnd.openxmlformats-officedocument.wordprocessingml.document');
        header('Content-Disposition: attachment;filename="'.$filename.'.docx"');
        header('Cache-Control: max-age=0');
        //html信息
        $html    = '<div style="font-size: 32px;">标题</div><p style="color: red;">描述</p>';
        $phpWord = new PhpWord();
        $section = $phpWord->addSection();


        // 添加带有链接的文本
        $linkText = '点击这里访问我的网站';
        $section->addText('这是一个链接示例：');
        $section->addLink($linkText, 'https://www.example.com');


        \PhpOffice\PhpWord\Shared\Html::addHtml($section, $html, false, false);
        $objWriter = \PhpOffice\PhpWord\IOFactory::createWriter($phpWord, 'Word2007');

        $objWriter->save('php://output');

        return $this->success([], 'html转换word成功');
    }

    // word模板替换（循环表格）（未测试）
    public function wordTable()
    {
        $path      = public_path().'/';
        $path      = app()->basePath().'/public/';
        $wordFile  = $path.'易见舆情日报.docx';
        $newfile   = $path.'易见舆情日报'.date("Y年m月d日 H：i：s").'.docx';  // 新文件名
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);

        //此处替换word文档中的对应变量值
        $processor->setValue('date', date("Y年m月d日"));
        /*$processor->setValue('JIDCode', '测试');
        $processor->setValue('JLegalRepresentative', '测试');*/


        //克隆行 第一个参数为表格中的某列的字段 第二个参数为需要克隆的行数
        $list  = $this->data();
        $count = count($list);
        $processor->cloneRow('thTitle', $count);//复制行
        $processor->cloneRow('thDescription', $count);//复制行
        $processor->cloneRow('thUrl', $count);//复制行
        foreach($list as $key => $item){
            $processor->setValue("thTitle#".($key + 1), $item['title']); //替换变量
            $processor->setValue("thAuthor#".($key + 1), $item['author']);
            $processor->setValue("thDescription#".($key + 1), $item['description']);
            $processor->setValue("thUrl#".($key + 1), $item['link']);
        }

        /*$arr_onef = [];
        for($a = 0; $a < count($FJname); $a++){
            $ar_two['FJname']   = $FJname[$a];
            $ar_two['FJbrand']  = $FJbrand[$a];
            $ar_two['FJunit']   = $FJunit[$a];
            $ar_two['FJnumber'] = $FJnumber[$a];
            array_push($arr_onef, $ar_two);
        }
        //上面是查询需要赋值的数据总数
        $rows = count($arr_onef);//总行数
        //克隆行 第一个参数为表格中的某列的字段 第二个参数为需要克隆的行数
        $processor->cloneRow('FJname', $rows);//复制行
        for($i = 0; $i < $rows; $i++){
            $processor->setValue("FJname#".($i + 1), $arr_onef[$i]['FJname']);//替换变量
            $processor->setValue("FJbrand#".($i + 1), $arr_onef[$i]['FJbrand']);
            $processor->setValue("FJunit#".($i + 1), $arr_onef[$i]['FJunit']);
            $processor->setValue("FJnumber#".($i + 1), $arr_onef[$i]['FJnumber']);
        }*/

        //保存word  存放位置可以自定义
        $processor->saveAs($newfile);

        return $this->success();
    }

    // word模板替换（循环）成功
    public function wordLoop()
    {
        $path      = public_path().'/';
        $path      = app()->basePath().'/public/';
        $wordFile  = $path.'易见舆情日报.docx';
        $newfile   = $path.'易见舆情日报'.date("Y年m月d日 H：i：s").'.docx';  // 新文件名
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);

        //此处替换word文档中的对应变量值
        $processor->setValue('date', date("Y年m月d日"));
        /*$processor->setValue('JIDCode', '测试');
        $processor->setValue('JLegalRepresentative', '测试');*/

        /**
         * *** word的内容
         * ${block_name2}
         * ${thTitle}（${thAuthor}）
         * ${thDescription}
         * 链接：${thUrl}
         * ${/block_name2}
         */
        // 如果是循环数据
        $list    = $this->data();
        $replace = [];
        foreach($list as $item){
            $descripte = str_repeat($item['description'], rand(100, 300));
            $htmlLink  = "<a href='".$item['link']."'>".$item['link']."</a>";
            $htmlLink  = $item['link'];
            $replace[] = ['thTitle' => $item['title'], 'thAuthor' => $item['author'], 'thDescription' => $descripte, 'thUrl' => $htmlLink];
        }
        $processor->cloneBlock('block_name2', 0, true, false, $replace);

        /**
         * *** word的内容
         * ${block_name}
         * Customer: ${customer_name}
         * Address: ${customer_address}
         * ${/block_name}*/
        // 循环操作
        $replacements = array(
            array('customer_name' => 'Batman', 'customer_address' => 'Gotham City'),
            array('customer_name' => 'Superman', 'customer_address' => 'Metropolis'),
        );
        $processor->cloneBlock('block_name', 0, true, false, $replacements);

        //保存word  存放位置可以自定义
        $processor->saveAs($newfile);

        return $this->success();
    }

    // word 直接替换模板文件（成功）
    public function wordReplace()
    {
        $path      = public_path().'/';
        $path      = app()->basePath().'/public/';
        $wordFile  = $path.'易见舆情日报.docx';
        $newfile   = $path.'易见舆情日报'.date("Y年m月d日 H：i：s").'.docx';  // 新文件名
        $processor = new \PhpOffice\PhpWord\TemplateProcessor($wordFile);

        //此处替换word文档中的对应变量值
        $processor->setValue('date', date("Y年m月d日"));
        /*$processor->setValue('JIDCode', '测试');
        $processor->setValue('JLegalRepresentative', '测试');*/

        //保存word  存放位置可以自定义
        $processor->saveAs($newfile);

        return $this->success();
    }

    // 需要保存到Word中的数据
    protected function data()
    {
        return [
            ['title' => '你好', 'ctime' => '156881', 'description' => '描述', 'link' => 'https://www.baidu.com/', 'author' => '中国证券报',],
            ['title' => '你好', 'ctime' => '156881', 'description' => '描述', 'link' => 'https://www.baidu.com/', 'author' => '中国证券报',],
            ['title' => '你好', 'ctime' => '156881', 'description' => '描述', 'link' => 'https://www.baidu.com/', 'author' => '中国证券报',],
        ];
    }
}


